#!/usr/bin/python3
import os
import sys
import datetime
import requests
import argparse
import traceback
import subprocess

headers = {"Content-type": "application/json"}
FS_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/596839f6-7241-4e81-b8cf-bca30c299c51"
REPO_ADDR = "registry-vpc.cn-hangzhou.aliyuncs.com/xmov/"
BRANCH_TAG_MAP = {
    'develop': 'dev',
    'master': 'latest'
}
DEFAULT_TAG = 'dev'


def post_to_feishu(msg):
    result = requests.post(FS_URL, json=msg, headers=headers)
    print(result.json())


def gen_msg_body(project, branch, docker_tag):
    dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    msg_body = "%s, 项目[%s]基于[%s]分支的image已经构建完成,image tag=[%s],可以进行部署了." % (dt, project, branch, docker_tag)
    return msg_body


def git(*args):
    return subprocess.check_call(['git'] + list(args))


def docker(*args):
    return subprocess.check_call(['docker'] + list(args))


def main(project, branch, group):
    docker_tag = BRANCH_TAG_MAP.get(branch, DEFAULT_TAG)

    if branch.startswith("release"):
        docker_tag = 'release'

    if branch.startswith("hotfix"):
        docker_tag = 'release'

    # do build work
    image_name = project
    build_version = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    git_url = "git@git.xmov.ai:%s/%s.git" % (group, project)
    git("clone", git_url, "-b", branch, "--depth=1")

    image_title = "%s%s:%s" % (REPO_ADDR, image_name, docker_tag)
    image_version = "%s%s:%s" % (REPO_ADDR, image_name, build_version)
    pc="-pc"
    image_pc_title = "%s%s%s:%s" % (REPO_ADDR, image_name, pc, docker_tag)
    image_pc_version = "%s%s%s:%s" % (REPO_ADDR, image_name, pc, build_version)

    try:
        if branch == "master":
            docker("build", "--build-arg", "env=prod", "--no-cache", "-t", image_title, ".")
            docker("build", "--build-arg", "env=prod-pc", "--no-cache", "-t", image_pc_title, ".")
        elif branch == 'develop':
            docker("build", "--build-arg", "env=dev", "--no-cache", "-t", image_title, ".")
            docker("build", "--build-arg", "env=dev-pc", "--no-cache", "-t", image_pc_title, ".")            
        else:
            docker("build", "--build-arg", "env=test", "--no-cache", "-t", image_title, ".")
            docker("build", "--build-arg", "env=test-pc", "--no-cache", "-t", image_pc_title, ".")

        docker("tag", image_title, image_version)
        docker("push", image_title)
        docker("push", image_version)

        docker("tag", image_pc_title, image_pc_version)
        docker("push", image_pc_title)
        docker("push", image_pc_version)

        # post message to dingtalk
        msg_body = gen_msg_body(project, branch, docker_tag)
        msg = {
            "msg_type": "text",
            "content": {
                "text": msg_body,
            },
        }
        post_to_feishu(msg)
    except:
        print(traceback.format_exc())
        sys.exit(1)
    finally:
        # clean dir
        subprocess.check_call(["rm", "-rf", image_name])


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--project')
    parser.add_argument('--branch')
    parser.add_argument('--git-group')
    args = parser.parse_args()
    project = args.project
    branch = args.branch
    group = args.git_group
    main(project, branch, group)
